var userLogModel = require('../models/user-log'),
    activityModel = require('../models/activity'),
    apiHandler = require('../services/api-handler'),
    fs = require('fs'),
    writeCSV = require('write-csv'),
    jsonexport = require('jsonexport'),
    json2csv = require('json2csv'),
    config = require('../config/config'),
    crypto = require('crypto'),
    json2csv = require('json2csv');

exports.createLog = function (req, res) {
    var bodyParams = req.body;
    var userLog = new userLogModel({
        "user": req.user._id,
        "action": bodyParams.action,
        "target": bodyParams.target
    });
    userLogModel.createLog(userLog, apiHandler.handler.check(res, 'NO_LOGS', function (logs) {
        apiHandler.setSuccessResponse(logs, res);
    }));
};

exports.getAllLogs = function (req, res) {
    userLogModel.getAllLogs(apiHandler.handler.check(res, 'NO_LOGS', function (logs) {
        apiHandler.setSuccessResponse(logs, res);
    }));
};

exports.getAllLogsByDate = function (req, res) {
    userLogModel.getAllLogsByDate(req.body, apiHandler.handler.check(res, 'NO_LOGS', function (logs) {
        userLogModel.getAllLogsByDateCount(req.body, apiHandler.handler.check(res, 'NO_LOGS', function (logsCount) {
            var data = {
                logCount: logsCount.length,
                logList: logs
            };
            apiHandler.setSuccessResponse(data, res);
        }));
    }));
};

exports.getUserLogs = function (req, res) {
    userLogModel.getUserLogsForTable(req.body.userId, apiHandler.handler.check(res, 'NO_LOGS', function (logs) {
        apiHandler.setSuccessResponse(logs, res);
    }));
};

exports.getAllLogsCSV = function (req, res) {
    var params = req.body,
        csvType = req.body.csvType;
    if (csvType == 'userLogs' && params.fromDate && params.toDate) {
        userLogModel.getAllLogsCSV(params, apiHandler.handler.check(res, 'NO_LOGS', function (logs) {
            crypto.randomBytes(10, function (err, buffer) {
                var token = buffer.toString('hex');
                var filePath = process.env.CSV_UPLOAD_DEST + token + '.csv';
                // writeCSV(filePath, logs);

                var fields = ['_id', 'updatedAt', 'createdAt', 'user', '__v', 'target', 'action', 'name'];
                try {
                    var result = json2csv({ data: logs, fields: fields });
                    fs.writeFile(filePath, result, function(err) {
                        if(err) {
                            return console.log(err);
                        }
                        apiHandler.setSuccessResponse(filePath, res);
                    });
                } catch (err) {
                    apiHandler.setErrorResponse('CSV_ERROR', res);
                }
            });
        }));
    } else if (csvType == 'activities' && params.fromDate && params.toDate) {
        activityModel.getAllUsersActivitiesCSV(req.body, apiHandler.handler.check(res, 'NO_ACTIVITY', function (activities) {
            activities.forEach(function (activity) {
                activity.comments = activity.comments.toString();
            });
            crypto.randomBytes(10, function (err, buffer) {
                var token = buffer.toString('hex');
                var filePath = process.env.CSV_UPLOAD_DEST + token + '.csv';
                // writeCSV(filePath, activities);

                var fields = ['_id', 'updatedAt', 'createdAt', 'idea', 'user', '__v', 'activityType', 'ideaTitle', 'ideaContent', 'comments', 'name'];
                try {
                    var result = json2csv({ data: activities, fields: fields });
                    fs.writeFile(filePath, result, function(err) {
                        if(err) {
                            return console.log(err);
                        }
                        apiHandler.setSuccessResponse(filePath, res);
                    });
                } catch (err) {
                    apiHandler.setErrorResponse('CSV_ERROR', res);
                }
            });
        }));
    } else {
        apiHandler.setErrorResponse('REQUIRED_FIELDS_MISSING', res);
    }
};